﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Windows.Forms;

namespace SPAutomaticListsPopulator
{

    /// <summary>Batch helper
    /// </summary>
    public class BatchHelper
    {
        private static string getFieldValuesAsBatchedXML(BindingList<PopulatedFieldSetting> bindingFieldList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (PopulatedFieldSetting fieldSetting in bindingFieldList)
            {
                sb.Append(string.Format("<SetVar Name=\"{0}Title\">{1}</SetVar>",
                                            "urn:schemas-microsoft-com:office:office#",
                                            fieldSetting.InitialValue
                    ));
            }
            return sb.ToString();
        }

        public static void InsertItems(SPList _list, int itemsCount, BindingList<PopulatedFieldSetting> bindingFieldList)
        {
            using (SPSite site = new SPSite(_list.ParentWeb.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(_list.ParentWeb.ID))
                {
                    StringBuilder query = new StringBuilder();
                    query.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                    for (int itemCount = 0; itemCount < itemsCount; itemCount++)
                    {
                        query.AppendFormat("<Method ID=\"{0}\">" + // Any ID. does not matter
                        "<SetList>{1}</SetList>" +                 // Guid of the SPList
                        "<SetVar Name=\"ID\">New</SetVar>" +       // Incremental ID
                        "<SetVar Name=\"Cmd\">Save</SetVar>" +     // Batch insert
                         getFieldValuesAsBatchedXML(bindingFieldList) +
                        "</Method>",
                        "IsertItems", //0
                        _list.ID //1
                        );
                    }
                    query.Append("</Batch>");
                    web.ProcessBatchData(query.ToString());
                }
            }
        }


        public static void RemoveItems(SPList _list, string camlQuery)
        {
            SPWeb web = _list.ParentWeb;
            SPQuery query = new SPQuery();
            query.Query = camlQuery;

            SPListItemCollection items = _list.GetItems(query);
            int[] Ids = items.Cast<SPListItem>().Select(x => x.ID).ToArray();

            if (MessageBox.Show(string.Format("Are you sure you want to delete {0} items?",  Ids.Length), "Yes or no?",
                  MessageBoxButtons.YesNo,
                  MessageBoxIcon.Question,
                  MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
            {
                string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                   "<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

                StringBuilder sb = new StringBuilder();
                foreach (int id in Ids)
                {
                    sb.Append(
                        string.Format(@"<Method ID=""Del{0}"">
                                 <SetList Scope=""Request"">{1}</SetList> 
                                 <SetVar Name=""Cmd"">Delete</SetVar> 
                                 <SetVar Name=""ID"">{2}</SetVar> 
                                 </Method>", id, _list.ID, id)
                        );
                }

                string processtext = string.Format(batchFormat, sb.ToString());

                var result = web.ProcessBatchData(processtext);

                MessageBox.Show("Number of deleted items:" + items.Count.ToString());
            }
        }

        public static void RemoveItems(SPList _list, int firstItemId, int lastItemId)
        {
            string camlQuery = string.Format(@"<Where>
	            <And>
		            <Leq>
			            <FieldRef Name='ID' />
			            <Value Type='Counter'>{1}</Value>
		            </Leq>
		            <Geq>
			            <FieldRef Name='ID' />
			            <Value Type='Counter'>{0}</Value>
		            </Geq>
            </And> </Where>",
            firstItemId, lastItemId);

            RemoveItems(_list, camlQuery);
        }
    }
}
